package com.ruge.tool.autosign;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import com.ruge.tool.constants.Constants;
import com.ruge.tool.json.JsonTool;
import com.ruge.tool.sendMsg.DingDingTool;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 百度贴吧 签到
 *
 * @author ruge.wu
 * @version 2022-01-06 23:04
 **/
public class SignBaiDuTieBa {
    //我喜欢的贴吧 url
    public static final String MY_LIKE = "http://tieba.baidu.com/f/like/mylike";
    //贴吧地址
    public static final String INDEX_URL = "https://tieba.baidu.com";
    // 百度贴吧-签到
    public static final String SIGN = "https://tieba.baidu.com/sign/add";

    public static final Map<String, String> headers = new HashMap<>();

    static {
        headers.put("User-Agent", "Mozilla/5.0");
        headers.put("Accept-Language", "en-US,en;q=0.5");
        headers.put("Cookie", Constants.BAIDU_COOKIE);
    }

    /**
     * 获取我喜欢的贴吧（不带分页参数）
     */
    public static void getMyLike(String pn, List<Map<String, String>> list) {
        String result = HttpUtil.createPost(MY_LIKE + "?pn=" + pn).addHeaders(headers).execute().body();
        Pattern pattern = Pattern.compile("<tr><td>.+?</tr>");
        Matcher matcher = pattern.matcher(result);
        while (matcher.find()) {
            Document doc = Jsoup.parse(matcher.group());
            Elements link = doc.children();
            for (Element element : link) {
                String ex = Objects.requireNonNull(element.select(".cur_exp").first()).text();
                //等级
                String lv = Objects.requireNonNull(element.select(".like_badge_lv").first()).text();
                //等级名称
                String lvName = Objects.requireNonNull(element.select(".like_badge_title").first()).html();
                //贴吧ID（签到关键参数）
                String fid = Objects.requireNonNull(element.select("span").last()).attr("balvid");
                //贴吧名称
                String tbName = Objects.requireNonNull(element.select("a").first()).text();
                //贴吧地址
                String url = INDEX_URL + Objects.requireNonNull(element.select("a").first()).attr("href");
                list.add(MapUtil.builder(new HashMap<String, String>()).put("ex", ex).put("lv", lv).put("lvName", lvName).put("fid", fid).put("tbName", tbName).put("url", url).build());
            }
        }
        Document allDoc = Jsoup.parse(result);
        Elements el = allDoc.getElementsByClass("current");
        for (Element element : el) {
            if (element.nextElementSibling() != null) {
                String nextFn = Objects.requireNonNull(element.nextElementSibling()).text();
                getMyLike(nextFn, list);
            }
        }
    }

    /**
     * 一键签到所有贴吧
     */
    public static void exec() {
        Long start = System.currentTimeMillis();
        Map<String, Object> msg = new HashMap<>();
        //1.先获取用户关注的贴吧
        List<Map<String, String>> list = new ArrayList<>();
        getMyLike("1", list);
        int totalCount = list.size();
        //2.一键签到
        for (Map<String, String> map : list) {
            String url = SIGN + "?ie=utf-8&kw=" + map.get("tbName");
            String result = HttpUtil.createPost(url).addHeaders(headers).execute().body();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            map.put("no", JsonTool.getJsonToMap(result).get("no").toString());
        }
        long signCount = list.stream().filter((k) -> "0".equals(k.get("no"))).count();
        long signedCount = list.stream().filter((k) -> "1101".equals(k.get("no"))).count();
        msg.put("用户贴吧数", totalCount);
        msg.put("签到成功", signCount);
        msg.put("已签到", signedCount);
        msg.put("签到失败", (totalCount - signedCount - signCount));
        msg.put("耗时", (System.currentTimeMillis() - start) + "ms");
        DingDingTool.sendMsg("百度贴吧" + JsonTool.getObjToJson(msg));
    }
}
